package com.wolfword.crawler.server.controller;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageInfo;
import com.wolfword.common.domain.Result;
import com.wolfword.common.domain.ResultConstant;
import com.wolfword.common.util.object.StringUtil;
import com.wolfword.crawler.server.entity.RootUrlInfoEntity;
import com.wolfword.crawler.server.service.RootUrlInfoService;

/**
 * 单位（根网址）管理
 * @author ServerZhang
 * @date 2018年1月24日
 */
@RestController
@RequestMapping("/root")
public class RootUrlInfoController {
	
	private final Logger logger = LoggerFactory.getLogger(RootUrlInfoController.class);
	
	@Autowired
	private RootUrlInfoService rootUrlInfoService;
	
	/**
	 * 起始网址列表
     * @param request
     * @param url
     * @param containStr
     * @param status
     * @param pageIndex
     * @param pageSize
     * @return
     * @author ServerZhang
     * @date 2018年1月17日
     */
    @ApiOperation("起始网址列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "url", value = "地址中包含的串", paramType = "query", dataType = "string", required = false),
            @ApiImplicitParam(name = "orgName", value = "单位名称筛选", paramType = "query", dataType = "string", required = false),
            @ApiImplicitParam(name = "containStr", value = "爬取要求包含的串", paramType = "query", dataType = "string", required = false),
            @ApiImplicitParam(name = "status", value = "根网址爬取状态：0未加入到任务，1添加到任务（未完成），2已完成", paramType = "query", dataType = "Integer", required = false),
            @ApiImplicitParam(name = "pageIndex", value = "页码", paramType = "query", dataType = "Integer", required = false),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", paramType = "query", dataType = "Integer", required = false)
    })
	@PostMapping(value="/list")
	public Result list(HttpServletRequest request,
			String url, String orgName, String containStr,
			@RequestParam(value="status",defaultValue="-1")Integer status,
			@RequestParam(value="pageIndex",defaultValue="0")Integer pageIndex,
			@RequestParam(value="pageSize",defaultValue="50") Integer pageSize){
    	
    	if (status.equals(-1)) {
			status = null;
		}
    	
    	List<RootUrlInfoEntity> list = null;
    	Result result = null;
		try {
			list = rootUrlInfoService.list(url, orgName, containStr, status, pageIndex, pageSize);
			result = new Result(ResultConstant.SUCCESS,new PageInfo<>(list));
		} catch (Exception e) {
			logger.info(e.getMessage());
			e.printStackTrace();
			result = new Result(ResultConstant.GENERAL_ERROR.setMessage(e.getMessage()));
		}
		
	    return result;
	} 
    /**
     * 插入根网址
     * @param request
     * @param url
     * @param containStr
     * @author ServerZhang
     * @date 2018年1月17日
     */
    @ApiOperation("插入根网址")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "url", value = "地址", paramType = "query", dataType = "string", required = true),
    	@ApiImplicitParam(name = "orgName", value = "单位名称", paramType = "query", dataType = "string", required = false),
    	@ApiImplicitParam(name = "orgType", value = "单位类型", paramType = "query", dataType = "string", required = false),
    	@ApiImplicitParam(name = "containStr", value = "爬取要求包含的串", paramType = "query", dataType = "string", required = true),
    })
    @PostMapping(value="/insert")
    public Result insert(HttpServletRequest request,
    		String url,String orgName,String orgType, String containStr){
    	
    	if (StringUtil.isEmpty(url,containStr)) {
			return new Result(ResultConstant.EMPTY_PARAM.setMessage("参数不全"));
		}
    	
    	
    	Result result = null;
		try {
			RootUrlInfoEntity entity = new RootUrlInfoEntity();
			entity.setUrl(url);
			entity.setContainStr(containStr);
			entity.setOrgName(orgName);
			entity.setOrgType(orgType);
			rootUrlInfoService.insertAnd2Task(entity);
			Long id = entity.getId();
			if (id != null) {
				result = new Result(ResultConstant.SUCCESS,id);
			}else {
				result = new Result(ResultConstant.GENERAL_ERROR.setMessage("数据插入出错"));
			}
		} catch (Exception e) {
			logger.info(e.getMessage());
			e.printStackTrace();
			result = new Result(ResultConstant.GENERAL_ERROR.setMessage(e.getMessage()));
		}
    	return result;
    } 
    
    /**
     * 添加到任务
     * @param request
     * @param url
     * @param containStr
     * @author ServerZhang
     * @date 2018年1月17日
     */
    @ApiOperation("添加到任务")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "ids", value = "id串，用“,”隔开", paramType = "query", dataType = "string", required = false),
    })
    @PostMapping(value="/add2task")
    @Deprecated
    public void add2task(HttpServletRequest request,
    		String ids){
    	
    	if (StringUtil.isEmpty(ids)) {
    		return;
    	}
    	String[] split = ids.split("[,，]");
    	List<Long> idList = new ArrayList<Long>();
    	for(String str : split){
    		idList.add(Long.parseLong(str));
    	}
    	rootUrlInfoService.add2task(idList);
    } 
    
}
